package org.cx.comparator.map;

import org.cx.comparator.ComparatorConfiguration;
import org.cx.comparator.annotations.ComparatorMapping;
import org.cx.comparator.annotations.ComparatorMappings;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p> 通过注解指定映射方式的处理器  </p>
 *
 */
public class AnnotationProcessor extends MapProcessor {

    public AnnotationProcessor(ComparatorConfiguration comparatorConfiguration) {
        super(comparatorConfiguration);
    }

    @Override
    protected boolean matches(Method method) {
        return true;
    }

    @Override
    protected ComparatorMap doBuild(Method method) {
        ComparatorMappings comparatorMappings = AnnotationUtils.findAnnotation(method, ComparatorMappings.class);
        if (comparatorMappings == null) {
            comparatorMappings = ComparatorMappings.DEFAULT_MAPPINGS;
        }
        final ComparatorMapping[] mappings = comparatorMappings.value();

        final Set<ComparatorFieldMapping> fieldMappings = Arrays.stream(mappings)
                .map(mapping ->
                        new ComparatorFieldMapping(mapping.source(), mapping.target(),
                                mapping.equalsType(), mapping.expression(), mapping.fieldName(),
                                mapping.notEqualsSourceVal(),mapping.notEqualsTargetVal()))
                .collect(Collectors.toSet());
        final Class<?>[] parameterTypes = method.getParameterTypes();
        ComparatorMap comparatorMap = new ComparatorMap(parameterTypes[0], parameterTypes[1]);
        comparatorMap.setComparatorFieldMappings(fieldMappings);

        if (comparatorMappings.byDefault()) {
            buildByDefaultField(parameterTypes[0],parameterTypes[1], comparatorMap, comparatorMappings.excludes());
        }
        return comparatorMap;
    }
}
